﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Model;
using IBLL;
using BllFactory;
using System.IO;
using System.Text;
using System.Web;
using ETWebApi2.Models;

namespace ETWebApi2.Controllers
{
    
    [Route("personinfo"), JwtAuthActionFilter]
    public class PersonInfoController : ApiController
    {
        private ICUser_tbService m_userServer = ServiceFactory.CreatService<ICUser_tbService>();    
        /// <summary>
        /// 返回个人信息界面  以及相应二维码
        /// </summary>  
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage Get()
        {
            //CUser_tb currentUser = HttpContext.Current.Session["LoginInfo"] as CUser_tb;
            JwtAuthObject info = new BaseClass().GetInfoByToken(Request.Headers.Authorization.Parameter);
            CUser_tb user = m_userServer.GetList(u => u.Id == info.UserId).FirstOrDefault();
            //string WeixinCode = "";  //微信二维码
            //string token = GetWeiXinToken();  
            //if (token.Length > 4) 
            //{
            //    string ticket = GetWeiXinTicket(token, user.Id * 10 + 1);
            //    if (ticket.Length > 4)
            //        WeixinCode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + HttpUtility.UrlEncode(ticket);
            //    else
            //        WeixinCode = "image/logo.png";
            //}
            string companyName = new BaseClass().GetCompanyName((int)user.CompanyId);
            Person person = new Person(user,companyName);
            return ObjectToJson.toJson(new { status=200,data=new { total=1, rows = person } });
        } 

        private string GetWeiXinToken()
        {
            string sCorpKey = "51a41399f186564f5392e0cdfc1f0729"; //GetAK("WeiXinFwh"); // "ub3P7T1619Nqy-mLz-I_m09-IoCZ34gU7jbjvJRi3hS9YAu89EICQ0qY6kbcnyHc"; //程序Debug组的秘钥,有权发送消息
            string sCorpID = "wx06b50ea9b66d73f6";

            if (sCorpKey == null | sCorpID == null)
                return "";

            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", sCorpID, sCorpKey);

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Method = "GET";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = 0;

            //发送请求  
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            //得到返回结果   
            StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string rtn = php.ReadToEnd();  

            string name = "\"access_token\":";

            int index = rtn.IndexOf(name);
            if (index == -1)
                return "";
            else
            {
                index += name.Length;
                int start = rtn.IndexOf('"', index);
                if (start == -1)
                    return "";
                int end = rtn.IndexOf('"', start + 1);
                if (end == -1)
                    return "";

                return rtn.Substring(start + 1, end - start - 1);
            }
        }

        private string GetWeiXinTicket(string token, int id)
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={0}", token);

            //5分钟     
            string txt = "{\"expire_seconds\": 300, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + id.ToString() + "}}}";

            byte[] byteArray = Encoding.UTF8.GetBytes(txt);

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;

            Stream newStream = webRequest.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();

            //发送请求  
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            //得到返回结果  
            StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string rtn = php.ReadToEnd();

            string name = "\"ticket\":";

            int index = rtn.IndexOf(name);
            if (index == -1)
                return "";
            else
            {
                index += name.Length;
                int start = rtn.IndexOf('"', index);
                if (start == -1)
                    return "";
                int end = rtn.IndexOf('"', start + 1);
                if (end == -1)
                    return "";

                return rtn.Substring(start + 1, end - start - 1);
            }
        }


        /// <summary>
        /// 检查用户密码安全系数并提醒修改
        /// </summary>  
        /// <param name="id"></param>
        /// <returns></returns>
        //public string Getreminder(int id)
        //{
        //    CUser_tb user = userServer.GetList(u => u.Id == 35).FirstOrDefault();

        //    //1689M主管默认密码
        //    if (user.UserPwd.Length < 6 || user.UserPwd == "1688" || user.UserPwd == "1689M")
        //    {
        //        return "提醒：您现在的密码危险系数过高，请修改为安全密码，更换默认密码 或修改密码长度";
        //    }
        //    return "value";
        //}

        /// <summary>
        /// 个人信息修改  
        /// </summary>
        /// <param name="obj">密码 UserPwd 电话号码(Phone) 是否接收短信(ReadSM-->) 是否禁用自己(State )（相当于离开此公司）</param>
        [HttpPut]
        public HttpResponseMessage Put(CUser_tb user)
        {
            if (user == null)
                return ObjectToJson.toJson(new { status=201,error="信息传递有误"});
            if (m_userServer.Update(user))
                return ObjectToJson.toJson(new { status = 200, rel = true });
            else
                return ObjectToJson.toJson(new { status = 201, error = "信息修改失败" });
        }
    }
}
